package com.jd.learn.core.key;

import cn.hutool.core.util.StrUtil;
import com.jd.learn.core.key.IKeyCollector;
import com.jd.learn.domain.HotSwapModel;
import cn.hutool.core.collection.CollectionUtil;
import io.netty.util.internal.StringUtil;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author shenkaiwen5
 * @version 1.0
 * @date 2020/12/25
 */
public class TurnKeyCollector implements IKeyCollector<HotSwapModel, HotSwapModel> {
    ConcurrentHashMap<String, HotSwapModel> map0 = new ConcurrentHashMap<>();
    ConcurrentHashMap<String, HotSwapModel> map1 = new ConcurrentHashMap<>();

    private AtomicLong atomicLong = new AtomicLong(0);

    @Override
    public List<HotSwapModel> lockAndGetResult() {
        //自增后，对应map停止写入
        atomicLong.addAndGet(1);

        List<HotSwapModel> list;
        if (atomicLong.get() % 2 == 0) {
            list = get(map0);
            map0.clear();
        } else {
            list = get(map1);
            map1.clear();
        }
        return  list;
    }

    private List<HotSwapModel> get(ConcurrentHashMap<String, HotSwapModel> map) {
        return CollectionUtil.list(false, map.values());
    }

    @Override
    public void collect(HotSwapModel hotSwapModel) {
        String key = hotSwapModel.getKey();
        if (StrUtil.isEmpty(key)) {
            return;
        }
        if (atomicLong.get() % 2 == 0) {
            HotSwapModel model = map0.putIfAbsent(key, hotSwapModel);
            if (model != null) {
                model.setCount(hotSwapModel.getCount() + model.getCount());
            }
        } else {
            HotSwapModel model = map1.putIfAbsent(key, hotSwapModel);
            if (model != null) {
                model.setCount(hotSwapModel.getCount() + model.getCount());
            }
        }
    }
}
